package tech.yangzhijie.basic.knowledge.mianshi;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写不加锁会导致数据丢失，数据错误等一系列数据不一致问题
 * 重复读 覆盖写问题
 * 读写锁 提高读的效率 可以多个线程进入读 而写只能一个线程进入
 */
public class Test04ReadWriteThread {

    public static void main(String[] args) {

        ReadWriteThreadData data = new ReadWriteThreadData();

        for (int i = 1; i <= 10; i++) {
            final int num = i;
            new Thread(()->{
                data.write(num);
            },String.valueOf(i)).start();
        }
        for (int i = 1; i <= 10; i++) {
            new Thread(()->{
                data.read();
            },String.valueOf(i)).start();
        }
    }
}

class ReadWriteThreadData{

    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

    private volatile int num;

    public void read(){
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 开始读取……");
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 读取完成 num: "+this.num);
        }finally {
            readLock.unlock();
        }
    }

    public void write(int num){
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 开始写入……"+num);

            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.num = num;
            System.out.println(Thread.currentThread().getName() + " 写入完成 num: "+num);
        }finally {
            writeLock.unlock();
        }
    }
}
